document.addEventListener('DOMContentLoaded', function() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');
    const allOrdersContainer = document.getElementById('allOrders');
    const pendingOrdersContainer = document.getElementById('pendingOrders');
    const paidOrdersContainer = document.getElementById('paidOrders');
    const deliveringOrdersContainer = document.getElementById('deliveringOrders');
    const completedOrdersContainer = document.getElementById('completedOrders');
    const orderDetailModal = document.getElementById('orderDetailModal');
    const closeDetail = document.getElementsByClassName('close')[0];
    const orderDetailContent = document.getElementById('orderDetailContent');
    const logoutBtn = document.getElementById('logoutBtn');
    const homeBtn = document.querySelector('.btn-home');
    
    // 订单数据
    let allOrders = [];
    
    // 从后端API获取用户订单
    function fetchUserOrders() {
        try {
            const user = JSON.parse(localStorage.getItem('user'));
            
            if (!user) {
                console.log('用户未登录');
                alert('请先登录');
                window.location.href = 'login.html';
                return;
            }
            
            console.log('获取到的用户信息:', user);
            const apiUrl = `http://localhost:5000/api/orders/user/${user.user_id}`;
            console.log('请求的API URL:', apiUrl);
            
            fetch(apiUrl)
                .then(response => {
                    console.log('响应状态码:', response.status);
                    console.log('响应headers:', response.headers);
                    
                    if (!response.ok) {
                        throw new Error('获取订单数据失败，状态码：' + response.status);
                    }
                    return response.json().catch(err => {
                        console.error('解析JSON失败:', err);
                        // 如果JSON解析失败，返回空数组
                        return [];
                    });
                })
                .then(data => {
                    console.log('收到的原始数据:', data);
                    
                    // 确保data是数组
                    if (!Array.isArray(data)) {
                        console.warn('数据不是数组，转换为空数组');
                        data = [];
                    }
                    
                    // 格式化订单数据
                    allOrders = data.map(order => ({
                        id: order.order_id || 0,
                        orderTime: order.order_time || new Date().toLocaleString(),
                        totalAmount: parseFloat(order.total_amount) || 0,
                        status: order.order_status || '未知',
                        items: Array.isArray(order.order_details) ? 
                            order.order_details.map(detail => ({
                                foodId: detail.food_id || 0,
                                foodName: detail.food_name || '未知菜品',
                                quantity: detail.quantity || 0,
                                price: parseFloat(detail.unit_price) || 0
                            })) : []
                    }));
                    
                    console.log('格式化后的订单数据:', allOrders);
                    
                    // 重新显示订单
                    tabBtns[0].click();
                })
                .catch(error => {
                    console.error('获取订单数据错误：', error);
                    console.error('错误堆栈：', error.stack);
                    alert('获取订单数据失败，请刷新页面重试\n错误详情：' + error.message);
                    // 即使出错也显示空订单列表
                    allOrders = [];
                    tabBtns[0].click();
                });
        } catch (error) {
            console.error('执行fetchUserOrders函数时出错：', error);
            alert('系统错误：' + error.message);
            allOrders = [];
            tabBtns[0].click();
        }
    }
    
    // 分类订单
    function getOrdersByStatus(status) {
        return allOrders.filter(order => order.status === status);
    }
    
    // 切换标签页
    function openTab(evt, tabName) {
        // 隐藏所有内容
        tabContents.forEach(content => {
            content.classList.remove('active');
        });
        
        // 移除所有按钮的激活状态
        tabBtns.forEach(btn => {
            btn.classList.remove('active');
        });
        
        // 显示当前标签页内容
        document.getElementById(tabName).classList.add('active');
        
        // 设置当前按钮为激活状态
        evt.currentTarget.classList.add('active');
        
        // 根据标签页显示相应的订单
        if (tabName === 'all') {
            displayOrders(allOrders, allOrdersContainer, true);
        } else if (tabName === 'pending') {
            displayOrders(getOrdersByStatus('待支付'), pendingOrdersContainer, true, true);
        } else if (tabName === 'paid') {
            displayOrders(getOrdersByStatus('已支付'), paidOrdersContainer, true);
        } else if (tabName === 'delivering') {
            displayOrders(getOrdersByStatus('配送中'), deliveringOrdersContainer, true);
        } else if (tabName === 'completed') {
            displayOrders(getOrdersByStatus('已完成'), completedOrdersContainer, true);
        }
    }
    
    // 显示订单列表
    function displayOrders(orders, container, showDetailBtn = false, showPayBtn = false) {
        container.innerHTML = '';
        
        if (orders.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #666;">暂无订单</p>';
            return;
        }
        
        orders.forEach(order => {
            const orderItem = document.createElement('div');
            orderItem.className = 'order-item';
            
            let statusClass = '';
            switch(order.status) {
                case '待支付':
                    statusClass = 'status-pending';
                    break;
                case '已支付':
                    statusClass = 'status-paid';
                    break;
                case '配送中':
                    statusClass = 'status-delivering';
                    break;
                case '已完成':
                    statusClass = 'status-completed';
                    break;
            }
            
            orderItem.innerHTML = `
                <div class="order-header">
                    <div>订单号: #${order.id}</div>
                    <div class="order-status ${statusClass}">${order.status}</div>
                </div>
                <div class="order-info">
                    <p>下单时间: ${order.orderTime}</p>
                    <p>总金额: ¥${order.totalAmount.toFixed(2)}</p>
                </div>
                <div class="order-actions">
                    ${showDetailBtn ? `<button class="btn-view-detail" data-id="${order.id}">查看详情</button>` : ''}
                    ${showPayBtn ? `<button class="btn-pay" data-id="${order.id}">去支付</button>` : ''}
                </div>
            `;
            
            container.appendChild(orderItem);
        });
        
        // 添加事件监听
        if (showDetailBtn) {
            document.querySelectorAll('.btn-view-detail').forEach(button => {
                button.addEventListener('click', viewOrderDetail);
            });
        }
        
        if (showPayBtn) {
            document.querySelectorAll('.btn-pay').forEach(button => {
                button.addEventListener('click', payOrder);
            });
        }
    }
    
    // 查看订单详情
    function viewOrderDetail(event) {
        const orderId = parseInt(event.target.getAttribute('data-id'));
        const order = allOrders.find(o => o.id === orderId);
        
        if (order) {
            // 显示订单详情
            let itemsHtml = '';
            order.items.forEach(item => {
                itemsHtml += `
                    <tr>
                        <td>${item.foodName}</td>
                        <td>${item.quantity}</td>
                        <td>¥${item.price.toFixed(2)}</td>
                        <td>¥${(item.price * item.quantity).toFixed(2)}</td>
                    </tr>
                `;
            });
            
            orderDetailContent.innerHTML = `
                <h2>订单详情</h2>
                <div class="order-info">
                    <p><strong>订单号:</strong> #${order.id}</p>
                    <p><strong>下单时间:</strong> ${order.orderTime}</p>
                    <p><strong>状态:</strong> ${order.status}</p>
                </div>
                <table class="order-items-table">
                    <tr>
                        <th>菜品名称</th>
                        <th>数量</th>
                        <th>单价</th>
                        <th>小计</th>
                    </tr>
                    ${itemsHtml}
                </table>
                <div class="order-total">
                    <h3>总金额: ¥${order.totalAmount.toFixed(2)}</h3>
                </div>
            `;
            
            orderDetailModal.style.display = 'block';
        }
    }
    
    // 支付订单
    function payOrder(event) {
        const orderId = parseInt(event.target.getAttribute('data-id'));
        
        // 调用后端API支付订单
        fetch(`http://localhost:5000/api/orders/${orderId}/pay`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('支付订单失败');
            }
            return response.json();
        })
        .then(data => {
            // 重新获取订单数据
            fetchUserOrders();
            alert('支付成功');
        })
        .catch(error => {
            console.error('支付订单错误：', error);
            alert('支付失败：' + error.message);
        });
    }
    
    // 事件监听
    tabBtns.forEach(btn => {
        btn.addEventListener('click', function(evt) {
            const tabName = this.getAttribute('data-tab');
            openTab(evt, tabName);
        });
    });
    
    closeDetail.addEventListener('click', function() {
        orderDetailModal.style.display = 'none';
    });
    
    window.addEventListener('click', function(event) {
        if (event.target === orderDetailModal) {
            orderDetailModal.style.display = 'none';
        }
    });
    
    logoutBtn.addEventListener('click', function() {
        // 清除用户信息
        localStorage.removeItem('user');
        
        // 跳转到登录页面
        window.location.href = 'login.html';
    });
    
    homeBtn.addEventListener('click', function() {
        // 跳转到学生主页
        window.location.href = 'student_home.html';
    });
    
    // 初始化页面，获取并显示订单
    fetchUserOrders();
    
    // 获取用户信息
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('username').textContent = `欢迎，${user.username}`;
    }
});